package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"word/cache"
	"word/models"
)

type WordController struct {
	beego.Controller
}

func (c *WordController) Add() {
	title := c.GetString("title")
	name := c.GetString("name")
	area := c.GetString("area")
	static := c.GetString("static")
	if title == "" || name == "" || area == "" || static == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "请检查是否有能容为空",
		}
		c.ServeJSON()
		return
	}
	var word models.Word
	word.Title = title
	word.Name = name
	word.Area = area
	word.Static = static
	if word.Add() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	key, _ := word.List()
	Keys, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, "redis_word", Keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *WordController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	name := c.GetString("name")
	area := c.GetString("area")
	static := c.GetString("static")
	var word models.Word
	word.ID = uint(id)
	word.Title = title
	word.Name = name
	word.Area = area
	word.Static = static
	if word.Update() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "修改失败",
		}
		c.ServeJSON()
		return
	}
	key, _ := word.List()
	Keys, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, "redis_word", Keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "修改成功",
	}
	c.ServeJSON()
	return
}
func (c *WordController) Del() {
	id, _ := c.GetInt("id")
	var word models.Word
	word.ID = uint(id)
	if word.Del() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	key, _ := word.List()
	Keys, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, "redis_word", Keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
func (c *WordController) List() {
	JsonRData := cache.Rdb.Get(cache.Ctx, "List").Val()
	var word []*models.Word
	if JsonRData == "" {
		models.DB.Find(&word)
		RedisData, _ := json.Marshal(word)
		cache.Rdb.Set(cache.Ctx, "List", RedisData, 0)
	} else {
		json.Unmarshal([]byte(JsonRData), &word)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "查询成功",
		"data": word,
	}
	c.ServeJSON()
	return
}
